package org.mathcloud.math.core.scilab.operator.algebra;

import org.apache.log4j.Logger;
import org.mathcloud.math.core.common.operator.algebra.Max;
import org.mathcloud.math.core.common.quantity.QuantityObject;
import org.mathcloud.math.core.scilab.factory.ScilabQuantityObjectFactory;
import org.mathcloud.math.core.scilab.manager.ScilabSupervisor;
import org.mathcloud.math.core.scilab.operator.ScilabNaryOperator;
import org.mathcloud.math.core.scilab.quantity.ScilabQuantityObject;
import org.scilab.modules.javasci.JavasciException;
import org.scilab.modules.types.ScilabDouble;

public class ScilabMax extends ScilabNaryOperator implements Max
{
	public ScilabMax()
	{
		super();
		signature.setMMLContentTag("max");
	}
	
	@Override 
	public void calculate()
	{
		if (getResultSignature()!=null)
    {
			if ((operands!=null)&&(operands.size()>1))
			{
				String sciJob;
	      String tmpVar1 = "tmp_"+ScilabSupervisor.getVarId();
	      ScilabQuantityObject tOp  = ScilabQuantityObjectFactory.getInstance(operands.get(0));
				sciJob = tOp.getVarName();
				for (int i=1;i<operands.size();i++)				
				{
					tOp  = ScilabQuantityObjectFactory.getInstance(operands.get(i));
					sciJob = sciJob + "," + tOp.getVarName();
				}
				sciJob = tmpVar1+"=max(" + sciJob+"); ";
	      if (sciEngine.exec(sciJob))
	      {
	      	log.info(sciJob);
	      	try
					{
	      		ScilabDouble tRes = (ScilabDouble)sciEngine.get(tmpVar1);
		      	res = ScilabQuantityObjectFactory.getInstance(tRes);
						sciJob = "clear "+tmpVar1+";";
						if (sciEngine.exec(sciJob))
							log.info(sciJob);					      	
					} catch (JavasciException e)
					{
						log.error(e);
					}
	      }
	      else
	      {
	      	res = null;
	      	log.info(sciJob);
	      	log.info(sciEngine.getLastErrorMessage());
	      }				
			}
    }    						
	}
	
	@Override
	public QuantityObject calculate(QuantityObject arg0, QuantityObject arg1)
	{
		// TODO Auto-generated method stub
		return null;
	}
	
	private static final Logger log = Logger.getLogger(ScilabMax.class);
}
